import axios from "axios";
//参考文档 https://juejin.cn/post/6968630178163458084
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
function request(config, customOptions) {
    const service = axios.create({
        baseURL: '/api', //设置统一请求的前缀
        timeout: 100000, //设置统一的超时时长
        // headers: {
        //     'content-type': 'application/json'
        // },
    })
    // 自定义配置
    let custom_options = Object.assign({
        repeat_request_cancel: false, // 是否开启取消重复请求, 默认为 true
    }, customOptions);
    let loading

    service.interceptors.request.use(
        config => {
            removePending(config);
            custom_options.repeat_request_cancel && addPending(config);
            loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
              })
            return config;
        },
        error => {
            return Promise.reject(error);
        }
    );

    service.interceptors.response.use(
        response => {
            removePending(response.config);
            if (response.data.code !=200) {
                ElMessage.error(response.data.error);
            }
            
            loading.close()
            return response.data;
        },
        error => {
            error.config && removePending(error.config);
            ElMessage.error(error.message);
            loading.close()
            console.error(error)
            return Promise.reject(error);
        }
    );
    return service(config)
}
//以下是取消重复请求
const pendingMap = new Map()

function getPendingKey(config) {
    let {
        url,
        method,
        params,
        data
    } = config;
    if (typeof data === 'string') data = JSON.parse(data); // response里面返回的config.data是个字符串对象
    return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&');
}

//存储每个请求唯一值，也就是cancel()
function addPending(config) {
    const pendingKey = getPendingKey(config);
    config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
        if (!pendingMap.has(pendingKey)) {
            pendingMap.set(pendingKey, cancel);
        }
    });
}
//删除重复的请求
function removePending(config) {
    const pendingKey = getPendingKey(config);
    if (pendingMap.has(pendingKey)) {
        const cancelToken = pendingMap.get(pendingKey);
        cancelToken(pendingKey);
        pendingMap.delete(pendingKey);
    }
}

//生成每个请求唯一的键
export default request